<template>
  <view>
    <view
      class="input-content text-left"
      :focus.sync="textareaFocus"
      @input="textareaBInput"
      ref="input-content"
      placeholder="多行文本输入框"
      contenteditable="true"
    >
    </view>
    <choose-person
      :visible.sync="choosePersonVisible"
      @check-person="checkPerson"
    ></choose-person>
  </view>
</template>

<script>
import choosePerson from "./choose-person.vue";
export default {
  components: {
    choosePerson,
  },
  data() {
    return {
      // 内容
      oldContent: "",
      content: "",
      cursorIndex: 0, //光标的位置
      // 选择@人
      choosePersonVisible: false,
      textareaFocus: false,
    };
  },
  methods: {
    // 用户输入
    textareaBInput() {
      // 记录当前输入的内容
      this.content = this.$refs["input-content"].$el.innerHTML;
      const oldArr = this.oldContent.split("");
      const newArr = this.content.split("");
      let contentStr = this.content;
      // 找出当前输入的内容
      oldArr.forEach((str) => {
        contentStr = contentStr.replace(str, "");
      });
      // 输入是@时
      if (contentStr === "@") {
        this.choosePersonVisible = true;
        this.textareaFocus = false;

        // 比对算法,找出当前光标的位置,找到当前输入的位置
        newArr.some((now, index) => {
          if (
            this.content.substring(0, index) !==
            this.oldContent.substring(0, index)
          ) {
            this.cursorIndex = index;
            return true;
          }
          this.cursorIndex = 0;
        });
      }
      this.oldContent = this.content;
    },
    // 选择@的人
    checkPerson(data) {
      const span = `<span contenteditable="false" userName="${data.name}" userId="${data.personId}" style="color:#4A90E2;">@${data.name}</span>`;
      let html = this.$refs["input-content"].$el.innerHTML;
      // 光标位置为0在后面追加,不为0从中间替换
      if (this.cursorIndex) {
        html =
          html.substr(0, this.cursorIndex - 1) +
          span +
          html.substr(this.cursorIndex, html.length);
      } else {
        html = html.substr(0, html.length - 1) + span;
      }
      this.$refs["input-content"].$el.innerHTML = html;
      this.oldContent = this.$refs["input-content"].$el.innerHTML;

      this.choosePersonVisible = false;
      this.textareaFocus = true;
    },
  },
};
</script>

<style lang="scss">
.input-content {
  outline: none;
  margin: 16px 0 15px;
  height: 4.6em;
  width: 100%;
  line-height: 1.2em;
  -webkit-box-flex: 1;
  -webkit-flex: 1;
  flex: 1;
  font-size: 14px;
  padding: 0;
}
</style>